const fs = require("fs");
const path = require("path");
import { fileURLToPath } from "url";
import { dirname } from "path";
const __dirname = dirname(__filename);
const resolve = (dir) => path.join(__dirname, dir);
const filePath = resolve("../../pages.json"); //这里是pages的路径，要检查是否正确

interface Config {
  [key: string]: RouteOptions;
}

interface RouteOptions {
  path: string;
  name: string;
  title?: string;
  animaName?: string;
  openAnima?: boolean;
}

type Routes = Record<RouteOptions["name"], RouteOptions["path"]>;

interface ConfigRes {
  PAGES?: Config;
  ROUTES?: Routes;
}

// 路由名转换成驼峰
const toCamelCase = (str) => {
  return str.replace(/[-_](.)/g, (_, char) => char.toUpperCase());
};

// json文件去掉注释
const parseJSONWithComments = (jsonString: string) => {
  const jsonWithoutComments = jsonString.replace(/\/\/.*/g, "");
  return JSON.parse(jsonWithoutComments);
};

// fs读取文件后生成map映射文件
const getPagesMap = (pages: any[]): Config => {
  let map: Config = {};
  pages.forEach((route) => {
    const parts = route.path.split("/");
    const name = toCamelCase(parts[parts.length - 1]);
    map["/" + route.path] = {
      path: "/" + route.path,
      title: route.style?.navigationBarTitleText ?? "",
      animaName: route.animaName ?? "slide-in-right",
      name: name,
      openAnima: route.openAnima ?? true,
    };
  });
  return map;
};

// 映射路由
const getRoutes = (pagesMap: Config): Routes => {
  let routes: Routes = {};
  for (let key in pagesMap) {
    routes[pagesMap[key].name] = pagesMap[key].path;
  }
  return routes;
};

// 暴露出去
const PagesConfig = (): Promise<ConfigRes> => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, "utf8", (err, data) => {
      if (err) {
        reject({});
        throw `"the filePath is error:"${filePath}`;
      }
      const PAGES = getPagesMap(parseJSONWithComments(data).pages);
      const ROUTES = getRoutes(PAGES);
      resolve({ PAGES, ROUTES });
    });
  });
};

export default PagesConfig;
